﻿//-----------------------------------------------------------------------
// <copyright file="HiddenFieldWebflowContextProvider.cs" company="Sławomir Rosiek">
//     Copyright (c) Sławomir Rosiek. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace Rosieks.Web.Flow
{
    using System;
    using System.IO;
    using System.Web.Mvc;

    public class HiddenFieldWebflowContextProvider : IWebflowContextProvider
    {
        internal const string WebflowContextKey = "__WebflowContext__";
        private readonly LosFormatterBase formatter;

        /// <summary>
        /// Initializes a new instance of the <see cref="T:HiddenFieldWebflowContextProvider"/> class.
        /// </summary>
        public HiddenFieldWebflowContextProvider(LosFormatterBase formatter)
        {
            this.formatter = formatter;
        }

        public void SetContext(ControllerContext context, WebflowContext webflowContext)
        {
            if (webflowContext == null)
            {
                throw new ArgumentNullException("webflowContext");
            }

            using (var sw = new StringWriter())
            {
                formatter.Serialize(sw, webflowContext);
                context.Controller.ViewData[HiddenFieldWebflowContextProvider.WebflowContextKey] = sw.ToString();
            }
        }

        public void DeleteContext(ControllerContext context, WebflowContext webflowContext)
        {
            if (webflowContext == null)
            {
                throw new ArgumentNullException("webflowContext");
            }

            context.Controller.ViewData.Remove(HiddenFieldWebflowContextProvider.WebflowContextKey);
        }

        public WebflowContext GetContext(ControllerContext context, string webflowName)
        {
            string formattedWebflowContext = context.HttpContext.Request[HiddenFieldWebflowContextProvider.WebflowContextKey];
            if (!string.IsNullOrWhiteSpace(formattedWebflowContext))
            {
                return (WebflowContext)formatter.Deserialize(formattedWebflowContext);
            }

            return null;
        }
    }
}
